<template>
  <!-- v-loading="true" -->
  <div>
    <el-card shadow="never">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select style="width: 100%" v-model="serachForm.productclassoneid" placeholder="请选择一级分类"
            @change="selectChange">
            <el-option v-for="option in searchList" :key="option.px" :label="option.name" :value="option.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select style="width: 100%" v-model="serachForm.productclasstwoid" placeholder="请选择二级分类"
            @change="selectChangeTwo">
            <el-option v-for="option in productclasstwoList" :key="option.px" :label="option.name" :value="option.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-input v-model="serachForm.name" placeholder="请输入产品名字" />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="onSubmit">搜索</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- <pageSearch :searchFormConfig="searchFormConfigRef" @searchSubmit="searchSubmit" /> -->
    <pageTable :tableData="tableData" :tableInit="params.tableInit" @sizeChange="sizeChange"
      @currentChange="currentChange" @exportFn="exportExcel" v-loading="loading" @pageAdd="openDialogFn('新增')">
      <template #status="{ row }">
        {{ filterStatus(row.status) }}
      </template>
      <template #px="{ row }">
        <el-tag>{{ row.px }}</el-tag>
      </template>
      <template #operation="{ row }">
        <el-button type="primary" link @click="openDialogFn('编辑', row)">编辑</el-button>
        <el-popconfirm title="确认要删除吗?" @confirm="delData(row.id)">
          <template #reference>
            <el-button type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>



    </pageTable>

    <Dialog width="60%" top="5vh" ref="DialogRef" :title="typeText" @submit="submitForm(ruleFormRef)"
      @onclose="resetForm(ruleFormRef)">
      <el-form ref="ruleFormRef" v-loading="DialoLoading" :model="ruleForm" status-icon :rules="rules"
        label-width="120px" class="demo-ruleForm">

        <el-row :gutter="20">

          <el-col :span="24">
            <div>产品基本信息</div>
            <el-divider />
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="ruleForm.name" autocomplete="off" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品状态" prop="status">
              <el-select style="width: 100%" v-model="ruleForm.status" placeholder="请选择产品状态">
                <el-option v-for="option in productStatus" :key="option.id" :label="option.name" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="产品简介" prop="description">
              <el-input v-model="ruleForm.description" autocomplete="off" placeholder="请输入产品简介"
                :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="产品排序">
              <el-input style='width:200px' type='number' v-model="ruleForm.px" autocomplete="off"
                placeholder="请输入产品排序" />
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="工作温度" prop="description">
              <el-row class="w-[60%]">
                <el-col :span="10">
                  <el-input v-model="ruleForm.minwd" autocomplete="off" placeholder="请输入" />
                </el-col>
                <el-col :span="4">
                  <div class="w-full flex justify-center">--</div>
                </el-col>
                <el-col :span="10">
                  <el-input v-model="ruleForm.maxwd" autocomplete="off" placeholder="请输入" />
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="数据表" v-if='!DialoLoading'>
              <uploadFiles v-model="ruleForm.linklist" @onPreviewFn="onPreviewFN" :limit="10"></uploadFiles>
            </el-form-item>
          </el-col>



          <el-col :span="24">
            <el-form-item label="产品图片" prop="productImg" v-if='!DialoLoading'>
              <LTUpload v-model="ruleForm.productImg" :limit="5" tip="最多5张，建议图片尺寸为1800 x 1200px"></LTUpload>
            </el-form-item>
          </el-col>



          <el-col :span="8">
            <el-form-item label="产品分类" prop="productclassoneid">
              <el-select style="width: 100%" v-model="ruleForm.productclassoneid" placeholder="请选择一级菜单"
                @change="selectChangeForm">
                <el-option v-for="option in searchList" :key="option.id" :label="option.name" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="" prop="productclasstwoid" label-width="0">
              <el-select @change="selectChangeFormTwo" style="width: 100%" v-model="ruleForm.productclasstwoid"
                placeholder="请选择二级菜单">
                <el-option v-for="option in productclasstwoFormList" :key="option.id" :label="option.name"
                  :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>



          <el-col :span="12">
            <el-form-item label="新品周期">
              <el-input v-model="ruleForm.syday" type="number" autocomplete="off" placeholder="请输入剩余天数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否首页展示">
              <el-switch v-model="ruleForm.homepa" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="产品参数" prop="sszdid">
              <el-row>
                <el-col :span="24">
                  <el-select style="width: 40%" v-model="ruleForm.sszdid" placeholder="请选择产品字典"
                    @change="selectChangeFormSszdid">
                    <el-option v-for="option in selpageList" :key="option.id" :label="option.name" :value="option.id" />
                  </el-select>
                </el-col>
                <el-col :span="24" class="mt-4">
                  <el-card shadow="never">
                    <el-row :gutter="20" v-for="(item, index) in  ruleForm.sjmap " :key="index">
                      <el-col :span="8">
                        <el-input :disabled="item.disabled" v-model="item.key" autocomplete="off"
                          placeholder="请输入参数标题" />
                      </el-col>
                      <el-col :span="10">
                        <el-input v-model="item.value" autocomplete="off" placeholder="请输入参数值" />
                      </el-col>
                      <el-col :span="6">
                        <el-switch class="mb-2" :disabled="!item.disabled" v-model="item.isshow" :active-value="0"
                          :inactive-value="1" active-text="在产品详情页中展示" />
                      </el-col>
                    </el-row>

                    <el-button @click="addsjmapFn">添加新段落</el-button>

                  </el-card>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="产品封装">
              <el-select collapse-tags collapse-tags-tooltip multiple style="width: 20%" v-model="ruleForm.cpfz"
                placeholder="请选择">
                <el-option v-for=" option  in  selpackagepageList " :key="option.id" :label="option.paccode"
                  :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="产品说明">
              <el-row class="w-full">
                <el-col :span="24" class="mb-[15px]" v-for="( item, index ) in  ruleForm.cpsm " :key="index">
                  <el-input v-model="item.description" autocomplete="off" placeholder="请输入产品说明" />
                </el-col>
                <el-col :span="24" class="">
                  <el-button @click="addruleFormcpsm">添加新段落</el-button>
                </el-col>
              </el-row>

            </el-form-item>
          </el-col>


          <el-col :span="24" class="mt-8">
            <div>产品设计和开发</div>
            <el-divider />
          </el-col>

          <el-col :span="24">
            <el-form-item label="评估板">
              <el-select collapse-tags collapse-tags-tooltip style="width: 20%" multiple v-model="ruleForm.pgb"
                placeholder="请选择">
                <el-option v-for=" option  in  pingGuList " :key="option.id" :label="option.name" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="仿真文件">
              <el-select collapse-tags collapse-tags-tooltip style="width: 20%" multiple v-model="ruleForm.fzwj"
                placeholder="请选择">
                <el-option v-for=" option  in  selfzwjpageList " :key="option.id" :label="option.name"
                  :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>






          <el-col :span="24" class="mt-8">
            <div>技术文档</div>
            <el-divider />
          </el-col>

          <el-col :span="24">
            <el-form-item label="" label-width="0">
              <el-row class="w-full pb-4" v-if="ruleForm.jswdlist.length > 0">

                <el-col :span="4" class="text-center">
                  文档/文章
                </el-col>

                <el-col :span="3" class="text-center">
                  文档类型
                </el-col>
                <el-col :span="6" class="text-center">
                  文档
                </el-col>
                <!-- <el-col :span="3" class="text-center">
                  文档格式
                </el-col> -->
                <el-col :span="4" class="text-center">
                  文档权限
                </el-col>
                <el-col :span="4" class="text-center">
                  文档时间
                </el-col>
                <el-col :span="3" class="text-center">
                  操作
                </el-col>
              </el-row>
              <el-row class="w-full " v-if='!DialoLoading'>
                <el-col :span="24">
                  <template v-for="( v, index ) in  ruleForm.jswdlist " :key="v.webId">
                    <div class="mb-4">
                      <technicalFile @delItemFn="delItemFN" :itemIndex="index" :searchList="filesStatus"
                        v-model="ruleForm.jswdlist[index]"></technicalFile>

                    </div>
                  </template>
                </el-col>
              </el-row>


              <el-row class="w-full">
                <el-col :span="24">
                  <el-button @click="addtechnicalFile">添加文档</el-button>
                </el-col>
              </el-row>

            </el-form-item>
          </el-col>













        </el-row>
      </el-form>




      <el-dialog v-model="dialogTableVisible" title="预览">
        <pdfPage v-if="pdfUrl" :source='pdfUrl'></pdfPage>
      </el-dialog>









    </Dialog>

  </div>
</template>

<script setup lang="ts">
import pageTable from "@/components/base-ui/page-table";
import Dialog from "@/components/base-ui/dialog";
import { reactive, ref, computed } from 'vue'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { clone } from "@pureadmin/utils";
import { randomString } from '@/utils/xwCommon'
import { tableInit } from "./config/listTable.config";
import { usepageTable } from '@/components/base-ui/page-table/usePageTable'
import technicalFile from './components/technicalFile.vue'
import { getselpage } from '@/api/classification'
import uploadFiles from '@/components/base-ui/uploadFiles'
import LTUpload from '@/components/base-ui/upload'
import { getproductdictionaryselpage, productdictionaryselzdandzdinfo } from '@/api/productdictionary'
import { getselpackagepage, getselfzwjpage, getPingGuBan } from '@/api/designsupport'
import { productinserpro, productdelinfo, productgrclass, productselpage, getproductselproductinfo } from '@/api/productList'
import { getPicImg, geturlneeddl } from '@/api/upload'
import { message } from "@/utils/message";
import pdfPage from "@/components/base-ui/pdf";
import dayjs from "dayjs";


// 搜索
const serachForm = reactive({
  name: '',
  productclassone: '',  //一级产品类名称
  productclassoneid: '',  //一级产品类id（大类）
  productclasstwo: '',  //二级产品类名称（下级）
  productclasstwoid: '',  //二级产品类id（下级）
})
// 获取搜索下拉数据
const searchList = ref([])

const getSearchData = () => {
  getselpage().then(res => {
    searchList.value = res.result
  })
}

getSearchData()

const selectChange = (e) => {
  const item = searchList.value.find(v => v.id === e)
  if (item) {
    serachForm.productclassone = item.name
    serachForm.productclassoneid = e
    serachForm.productclasstwo = ''
    serachForm.productclasstwoid = ''
  }
}



const selectChangeTwo = (e) => {
  const item = productclasstwoList.value.find(v => v.id === e)
  if (item) {
    serachForm.productclasstwo = item.name
    serachForm.productclasstwoid = e
  }
}


// 获取产品字典
const selpageList = ref([])
const getselpageList = () => {
  getproductdictionaryselpage({
    index: 1,
    size: 10000
  }).then(res => {
    selpageList.value = res.result
  })
}
getselpageList()


// 获取产品字典详情
const selpageDetailList = ref([])
const selectChangeFormSszdid = (e) => {
  productdictionaryselzdandzdinfo(e).then(res => {
    selpageDetailList.value = res.result
    console.log(res.result)
    ruleForm.sjmap = res.result.map(v => {
      return {
        key: v.name,
        value: '',
        isshow: 0,
        disabled: true
      }
    })
  })
}

const addsjmapFn = () => {
  ruleForm.sjmap.push({
    key: '',
    value: '',
    isshow: 0,
    disabled: false
  })
}


// 获取封装文件信息
const selpackagepageList = ref([])
const getselpackagepageList = () => {
  getselpackagepage({
    index: 1,
    size: 10000
  }).then(res => {
    selpackagepageList.value = res.result
  })
}
getselpackagepageList()


// 分页查询仿真文件信息
const selfzwjpageList = ref([])
const getgetselfzwjpageList = () => {
  getselfzwjpage({
    index: 1,
    size: 10000
  }).then(res => {
    selfzwjpageList.value = res.result
    console.log(selfzwjpageList.value, 'selfzwjpageList.value')
  })
}
getgetselfzwjpageList()

// 查询评估板列表
const pingGuList = ref([])
const getpingGuList = () => {
  getPingGuBan({
    index: 1,
    size: 10000
  }).then(res => {
    pingGuList.value = res.result
  })
}
getpingGuList()




const onSubmit = () => {
  serachVal.value = serachForm
  getData()
}

const {
  exportExcel,
  tableData,
  getData,
  params,
  loading,
  sizeChange,
  serachVal,
  currentChange,
  delData,
  DialogRef,
  openDialog,
  productStatus,
  filesStatus,
  filterStatus
} = usepageTable({
  tableInit,
  getRes: productselpage,
  delRes: productdelinfo,
})

getData()






const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  name: '',
  status: '',
  description: '',
  linklist: [], // 数据表
  productImg: [], //产品图片
  productclassone: '',//一级产品类名称
  productclassoneid: '',//一级产品类id（大类）
  productclasstwo: '',//二级产品类名称（下级）
  productclasstwoid: '',//二级产品类id（下级）
  sszdid: '',  // 字典id
  sjmap: [],   // 详情字典入参  
  cpfz: [], // 封装文件
  cpsm: [],// 产品说明列表
  fzwj: [], //仿真文件
  jswdlist: [],// 技术文档
  syday: 0,   // 新品倒计时
  homepa: 0, //是否首页展示
  pgb: [],
  minwd: '',
  maxwd: '',
  px: 0
})

const validateList = (rule: any, value: any, callback: any) => {
  if (value.length === 0) {
    callback(new Error('请创建二级分类'))
  } else {
    let filterArray = value.filter(v => Boolean(v.name));
    if (filterArray.length === 0) {
      callback(new Error('请正确填写二级分类'))
    } else {
      callback()
    }
  }
}

const productclasstwoFormList = computed(v => {
  let item = searchList.value.find(v => ruleForm.productclassoneid == v.id)
  if (item) {
    return item?.list
  } else {
    return []
  }
})


const rules = reactive<FormRules<typeof ruleForm>>({
  name: [
    { required: true, message: '请填写一级菜单名称', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择产品状态', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请填写产品简介', trigger: 'blur' },
  ],
  productImg: [
    { required: true, message: '请上传产品图片，最多5张', trigger: 'blur' },
  ],
  productclassoneid: [
    { required: true, message: '请选择一级分类', trigger: 'blur' },
  ],
  productclasstwoid: [
    { required: true, message: '请选择二级分类', trigger: 'blur' },
  ],
  sszdid: [
    { required: true, message: '请选择产品字典', trigger: 'blur' },
  ],




  // list: [
  //   { validator: validateList, trigger: 'blur' }
  // ],

})


const addruleFormcpsm = () => ruleForm.cpsm.push({ description: '' })


const addtechnicalFile = () => ruleForm.jswdlist.push({ gs: '', level: 0, linkid: '', lx: '', name: '', createTime: dayjs().format("YYYY-MM-DD"), webId: randomString(10), infotype: 0, zdywzid: '' })

// 产品分类change
const selectChangeForm = (e) => {
  const item = searchList.value.find(v => v.id === e)
  if (item) {
    ruleForm.productclassone = item.name
    ruleForm.productclassoneid = e
    ruleForm.productclasstwo = ''
    ruleForm.productclasstwoid = ''
  }
}

const selectChangeFormTwo = (e) => {
  const item = productclasstwoFormList.value.find(v => v.id === e)
  if (item) {
    ruleForm.productclasstwo = item.name
    ruleForm.productclasstwoid = e
  }
}


// 表单二级分类列表
const productclasstwoList = computed(v => {
  let item = searchList.value.find(v => serachForm.productclassoneid == v.id)
  if (item) {
    return item?.list
  } else {
    return []
  }
})









const typeText = ref('')
const handleID = ref(null)
const DialoLoading = ref(false)
const openDialogFn = (text, row) => {
  DialoLoading.value = true
  typeText.value = text
  console.log(ruleForm, 'ruleForm')
  if (row) {
    handleID.value = row.id
    getproductselproductinfo(row.id).then(res => {

      const result = clone(res.result, true);

      Object.keys(ruleForm).forEach((key) => ruleForm[key] = result[key])


      ruleForm.linklist.forEach(v => {
        v.url = geturlneeddl(v.linkid)
      })

      ruleForm.productImg.forEach(v => {
        v.imgId = v.url
        v.url = getPicImg(v.url)
      })

      // 仿真文件列表
      // ruleForm.cpfz = result.fzwj
      // 封装列表
      // cpfz
      ruleForm.pgb = result.evloaboad.map(v => v.id)




      let fixedArray = result.sjmap.map(v => {
        return {
          key: v.name,
          value: v.valueinfo,
          isshow: v.ishow,
          disabled: true
        }
      })


      let dynamicArray = result.xzzdmap.map(v => {
        v.disabled = false
        return v
      })

      ruleForm.sjmap = [...fixedArray, ...dynamicArray]


      if (ruleForm.jswdlist.length > 0) {
        ruleForm.jswdlist.forEach(v => {
          v.webId = randomString(10)
        })
      }


    }).finally(() => {
      DialoLoading.value = false
    })
  } else {
    DialoLoading.value = false
  }
  openDialog()
}


const submitForm = (formEl: FormInstance | undefined) => {
  console.log(ruleForm)
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      setProduct()
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const setProduct = () => {

  const temporaryList = clone(ruleForm, true);
  console.log(temporaryList, 'temporaryList')
  // 处理数据表数据
  if (temporaryList.linklist.length > 0) {

    let a = temporaryList.linklist.map(v => {
      return {
        level: 0,
        linkid: v?.response?.data?.result[0]?.uuid ?? v.linkid,
        name: v.name
      }
    })
    temporaryList.linklist = a
  }

  // 处理图片
  if (temporaryList.productImg.length > 0) {
    let b = temporaryList.productImg.map(v => {
      return {
        name: v.name,
        url: v?.response?.data?.result[0]?.uuid ?? v.imgId,
      }
    })
    temporaryList.productImg = b
  }


  // 处理字典字段
  if (temporaryList.sjmap.length > 0) {
    // 过滤空
    let c = temporaryList.sjmap.filter(v => v.key)
    const temporary = clone(c, true);
    temporaryList.xzzdmap = temporary.filter(v => !v.disabled)
    temporaryList.sjmap = temporaryList.sjmap.filter(v => v.disabled)
  }
  // 产品说明列表
  if (temporaryList.cpsm.length > 0) {
    let c = temporaryList.cpsm.filter(v => v.description)
    temporaryList.cpsm = c
  }



  // 处理技术支持
  if (temporaryList.jswdlist.length > 0) {
    let f = temporaryList.jswdlist.filter(v => {
      if (v.infotype == 0) {
        if (v.linkid) {
          return v
        }
      }
      if (v.infotype == 1) {
        if (v.zdywzid) {
          return v
        }
      }
    })
    temporaryList.jswdlist = f
  }



  console.log(temporaryList.jswdlist, 'temporaryList')
  temporaryList.id = handleID.value
  let fn = typeText.value === '新增' ? productinserpro : productgrclass
  // if (typeText.value === '新增') {
  fn(temporaryList).then(res => {
    DialogRef.value.close()
    message("添加成功", {
      type: "success"
    });
    getData()
  })
  // }

}


const delItemFN = (index) => ruleForm.jswdlist.splice(index, 1)








const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()

  handleID.value = null


  ruleForm.name = ''
  ruleForm.status = ''
  ruleForm.description = ''
  ruleForm.linklist = []
  ruleForm.productImg = []
  ruleForm.productclassone = ''
  ruleForm.productclassoneid = ''
  ruleForm.productclasstwo = ''
  ruleForm.productclasstwoid = ''
  ruleForm.sszdid = ''
  ruleForm.sjmap = []
  ruleForm.cpfz = []
  ruleForm.cpsm = []
  ruleForm.fzwj = []
  ruleForm.jswdlist = []
  ruleForm.syday = 0
  ruleForm.homepa = 0
  ruleForm.pgb = []
  ruleForm.minwd = []
  ruleForm.maxwd = []
  ruleForm.px = 0

}



const dialogTableVisible = ref(false)
const pdfUrl = ref('')
const onPreviewFN = (e) => {
  pdfUrl.value = e
  dialogTableVisible.value = true
}
</script>

<style scoped>
:deep(.el-form-item__label) {
  font-weight: 600;
}
</style>
